package com.bank.ui.customer;

import com.bank.dao.CardDAO;
import com.bank.dao.TransactionDAO;
import com.bank.entity.Card;
import com.bank.entity.Transaction;
import com.bank.util.ValidationUtils;

import javax.swing.*;
import java.awt.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;

import java.util.logging.Logger;
public class CustomerDashboard extends JPanel {
    private final CardDAO cardDAO = new CardDAO();
    private final String customerId;
    private final String userPID;
    private JComboBox<String> cardComboBox;
    private JTabbedPane tabbedPane;
    private JPanel accountInfoPanel;
    private JPanel tradeRecordPanel;
    public CustomerDashboard(String customerId, String userPID){
        this.customerId = customerId;
        this.userPID = userPID;
        initializeUI();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 初始化tabbedPane
        tabbedPane = new JTabbedPane();
        tabbedPane.setFont(new Font("微软雅黑", Font.BOLD, 14));

        try {
            // 初始化面板并赋值给成员变量
            accountInfoPanel = createAccountInfoPanel();
            tradeRecordPanel = createTradeRecordPanel();

            tabbedPane.add("账户信息", accountInfoPanel);
            tabbedPane.add("交易记录", tradeRecordPanel);
            tabbedPane.add("存款", createDepositPanel());
            tabbedPane.add("取款", createWithdrawPanel());
            tabbedPane.add("转账", createTransferPanel());
            tabbedPane.add("挂失", createLossReportPanel());
            tabbedPane.add("修改密码", createChangePasswordPanel());

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "初始化界面失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }

        add(tabbedPane, BorderLayout.CENTER);

        // 添加标签切换监听器
        tabbedPane.addChangeListener(e -> refreshCurrentTab());
    }
    // 刷新当前选中的标签页
    private void refreshCurrentTab() {
        int index = tabbedPane.getSelectedIndex();
        if (index < 0) return;

        String title = tabbedPane.getTitleAt(index);
        JPanel newPanel = null;

        switch (title) {
            case "账户信息":
                newPanel = createAccountInfoPanel();
                accountInfoPanel = newPanel;
                break;
            case "交易记录":
                newPanel = createTradeRecordPanel();
                tradeRecordPanel = newPanel;
                break;
            // 其他面板按需添加
            default:
                return; // 不需要刷新的面板
        }

        tabbedPane.setComponentAt(index, newPanel);
    }

    // 刷新指定面板类型
    public void refreshPanel(Class<?> panelType) {
        for (int i = 0; i < tabbedPane.getTabCount(); i++) {
            Component comp = tabbedPane.getComponentAt(i);
            if (panelType.isInstance(comp)) {
                JPanel newPanel = null;

                if (panelType.equals(JPanel.class)) {
                    switch (tabbedPane.getTitleAt(i)) {
                        case "账户信息":
                            newPanel = createAccountInfoPanel();
                            accountInfoPanel = newPanel;
                            break;
                        case "交易记录":
                            newPanel = createTradeRecordPanel();
                            tradeRecordPanel = newPanel;
                            break;
                        default:
                            continue;
                    }
                }

                if (newPanel != null) {
                    tabbedPane.setComponentAt(i, newPanel);
                    if (tabbedPane.getSelectedIndex() == i) {
                        newPanel.revalidate();
                        newPanel.repaint();
                    }
                }
                break;
            }
        }
    }

    private JPanel createAccountInfoPanel() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 15, 0));
        JLabel titleLabel = new JLabel("账户信息概览");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        JTextArea accountTextArea = new JTextArea();
        accountTextArea.setEditable(false);
        accountTextArea.setFont(new Font("宋体", Font.PLAIN, 14));
        accountTextArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        try {
            List<Card> cards = cardDAO.getCardsByCustomerId(Integer.parseInt(customerId));
            if (cards.isEmpty()) {
                accountTextArea.append("您尚未开通任何银行卡账户");
            } else {
                accountTextArea.append(String.format("%-20s %-15s %-15s %-10s%n", "账户编号", "余额", "开户日期", "状态"));
                accountTextArea.append("--------------------------------------------------------------\n");
                for (Card card : cards) {
                    accountTextArea.append(String.format("%-20s %-15.2f %-15s %-10s%n",
                            card.getCardID(),
                            card.getBalance(),
                            card.getOpenDate(),
                            "是".equals(card.getIsReportLoss()) ? "已挂失" : "正常"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载账户信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }

        mainPanel.add(new JScrollPane(accountTextArea), BorderLayout.CENTER);
        return mainPanel;
    }

    private JPanel createTradeRecordPanel() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 15, 0));
        JLabel titleLabel = new JLabel("交易记录查询");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        JTextArea tradeTextArea = new JTextArea();
        tradeTextArea.setEditable(false);
        tradeTextArea.setFont(new Font("宋体", Font.PLAIN, 14));
        tradeTextArea.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        try {
            TransactionDAO transactionDAO = new TransactionDAO();
            List<Transaction> transactions = transactionDAO.getTransactionsByCustomerId(Integer.parseInt(customerId));
            if (transactions.isEmpty()) {
                tradeTextArea.append("暂无交易记录");
            } else {
                tradeTextArea.append(String.format("%-10s %-15s %-10s %-10s %-20s%n", "交易ID", "日期", "类型", "金额", "备注"));
                tradeTextArea.append("--------------------------------------------------------------------\n");
                for (Transaction transaction : transactions) {
                    tradeTextArea.append(String.format("%-10d %-15s %-10s %-10.2f %-20s%n",
                            transaction.getTradeID(),
                            transaction.getTradeDate(),
                            transaction.getTradeType(),
                            transaction.getTradeMoney(),
                            transaction.getRemark()));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载交易记录失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }

        mainPanel.add(new JScrollPane(tradeTextArea), BorderLayout.CENTER);
        return mainPanel;

    }

    private JPanel createDepositPanel() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        JLabel titleLabel = new JLabel("存款操作");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("存款信息"),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 银行卡选择
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("选择银行卡:"), gbc);

        cardComboBox = new JComboBox<>();
        cardComboBox.setPreferredSize(new Dimension(250, 30));
        try {
            List<Card> cards = cardDAO.getCardsByCustomerId(Integer.parseInt(customerId));
            for (Card card : cards) {
                cardComboBox.addItem(card.getCardID());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载银行卡信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
        gbc.gridx = 1;
        formPanel.add(cardComboBox, gbc);

        // 存款金额
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("存款金额:"), gbc);

        JTextField amountField = new JTextField(20);
        amountField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(amountField, gbc);

        // 密码
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(new JLabel("输入密码:"), gbc);

        JPasswordField passwordField = new JPasswordField(20);
        passwordField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(passwordField, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 30, 20));
        JButton depositButton = new JButton("确认存款");
        depositButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        depositButton.setPreferredSize(new Dimension(150, 35));

        // 存款按钮事件处理
        depositButton.addActionListener(e -> {
            String cardNumber = (String) cardComboBox.getSelectedItem();
            String amountText = amountField.getText();
            String password = new String(passwordField.getPassword());

            try {
                // 简单验证
                if (ValidationUtils.isNullOrEmpty(cardNumber) ||
                        ValidationUtils.isNullOrEmpty(amountText) ||
                        ValidationUtils.isNullOrEmpty(password)) {
                    JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                double amount = Double.parseDouble(amountText);
                if (!ValidationUtils.validateAmount(amount)) {
                    JOptionPane.showMessageDialog(this, "存款金额必须大于0且最多两位小数", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 检查卡是否挂失 - 关键修改点
                if (cardDAO.isCardReportedLoss(cardNumber)) {
                    JOptionPane.showMessageDialog(this, "存款失败：该卡已挂失！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 执行存款操作
                boolean success = cardDAO.deposit(cardNumber, password, amount);
                if (success) {
                    JOptionPane.showMessageDialog(this, "存款成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    // 清空输入字段
                    amountField.setText("");
                    passwordField.setText("");
                } else {
                    // 存款失败只可能是密码错误（因为挂失卡已提前检查）
                    JOptionPane.showMessageDialog(this, "存款失败：密码错误！", "操作失败", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的金额数字", "格式错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        buttonPanel.add(depositButton);

        // 添加面板到主面板
        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        return mainPanel;
    }
    private JPanel createWithdrawPanel() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        JLabel titleLabel = new JLabel("取款操作");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("取款信息"),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 银行卡选择
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("选择银行卡:"), gbc);

        JComboBox<String> cardComboBoxWithdraw = new JComboBox<>();
        cardComboBoxWithdraw.setPreferredSize(new Dimension(250, 30));
        try {
            List<Card> cards = cardDAO.getCardsByCustomerId(Integer.parseInt(customerId));
            for (Card card : cards) {
                cardComboBoxWithdraw.addItem(card.getCardID());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载银行卡信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
        gbc.gridx = 1;
        formPanel.add(cardComboBoxWithdraw, gbc);

        // 当前余额
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("当前余额:"), gbc);

        JTextField balanceField = new JTextField(20);
        balanceField.setEditable(false);
        balanceField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(balanceField, gbc);

        // 取款金额
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(new JLabel("取款金额:"), gbc);

        JTextField amountFieldWithdraw = new JTextField(20);
        amountFieldWithdraw.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(amountFieldWithdraw, gbc);

        // 密码
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(new JLabel("输入密码:"), gbc);

        JPasswordField passwordFieldWithdraw = new JPasswordField(20);
        passwordFieldWithdraw.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(passwordFieldWithdraw, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
        JButton checkBalanceButton = new JButton("查询余额");
        checkBalanceButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        checkBalanceButton.setPreferredSize(new Dimension(120, 30));
        checkBalanceButton.addActionListener(e -> {
            String cardNumber = (String) cardComboBoxWithdraw.getSelectedItem();
            try {
                if (ValidationUtils.isNullOrEmpty(cardNumber)) {
                    JOptionPane.showMessageDialog(this, "请先选择银行卡", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 检查卡是否挂失 - 新增检查
                if (cardDAO.isCardReportedLoss(cardNumber)) {
                    JOptionPane.showMessageDialog(this, "该卡已挂失，无法查询余额！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    balanceField.setText("");
                    return;
                }

                double balance = cardDAO.getCardBalance(cardNumber);
                balanceField.setText(String.format("%.2f", balance));
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "查询余额失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        JButton withdrawButton = new JButton("确认取款");
        withdrawButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        withdrawButton.setPreferredSize(new Dimension(150, 35));
        withdrawButton.addActionListener(e -> {
            String cardNumber = (String) cardComboBoxWithdraw.getSelectedItem();
            String amountText = amountFieldWithdraw.getText();
            String password = new String(passwordFieldWithdraw.getPassword());

            try {
                // 简单验证
                if (ValidationUtils.isNullOrEmpty(cardNumber) ||
                        ValidationUtils.isNullOrEmpty(amountText) ||
                        ValidationUtils.isNullOrEmpty(password)) {
                    JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                double amount = Double.parseDouble(amountText);
                if (!ValidationUtils.validateAmount(amount)) {
                    JOptionPane.showMessageDialog(this, "取款金额必须大于0且最多两位小数", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 检查卡是否挂失 - 关键修改点
                if (cardDAO.isCardReportedLoss(cardNumber)) {
                    JOptionPane.showMessageDialog(this, "取款失败：该卡已挂失！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double balance = cardDAO.getCardBalance(cardNumber);
                if (amount > balance) {
                    JOptionPane.showMessageDialog(this, "取款金额超过余额", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                boolean success = cardDAO.withdraw(cardNumber, password, amount);
                if (success) {
                    JOptionPane.showMessageDialog(this, "取款成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    // 清空输入字段并更新余额显示
                    amountFieldWithdraw.setText("");
                    passwordFieldWithdraw.setText("");
                    balanceField.setText(String.format("%.2f", balance - amount));
                } else {
                    // 取款失败只可能是密码错误（因为挂失卡已提前检查）
                    JOptionPane.showMessageDialog(this, "取款失败：密码错误！", "操作失败", JOptionPane.ERROR_MESSAGE);
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的金额数字", "格式错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        buttonPanel.add(checkBalanceButton);
        buttonPanel.add(withdrawButton);

        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        return mainPanel;
    }

    private JPanel createTransferPanel() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        JLabel titleLabel = new JLabel("转账操作");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("转账信息"),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 转出银行卡
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("转出银行卡:"), gbc);

        JComboBox<String> fromCardComboBox = new JComboBox<>();
        fromCardComboBox.setPreferredSize(new Dimension(250, 30));
        try {
            List<Card> cards = cardDAO.getCardsByCustomerId(Integer.parseInt(customerId));
            for (Card card : cards) {
                fromCardComboBox.addItem(card.getCardID());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载银行卡信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
        gbc.gridx = 1;
        formPanel.add(fromCardComboBox, gbc);

        // 转入银行卡
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("转入银行卡:"), gbc);

        JTextField toCardField = new JTextField(20);
        toCardField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(toCardField, gbc);

        // 转账金额
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(new JLabel("转账金额:"), gbc);

        JTextField amountField = new JTextField(20);
        amountField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(amountField, gbc);

        // 密码
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(new JLabel("输入密码:"), gbc);

        JPasswordField passwordField = new JPasswordField(20);
        passwordField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(passwordField, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
        JButton transferButton = new JButton("确认转账");
        transferButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        transferButton.setPreferredSize(new Dimension(150, 35));
        transferButton.addActionListener(e -> {
            String fromCardID = (String) fromCardComboBox.getSelectedItem();
            String toCardID = toCardField.getText();
            String amountText = amountField.getText();
            String password = new String(passwordField.getPassword());

            try {
                // 简单验证
                if (ValidationUtils.isNullOrEmpty(fromCardID) ||
                        ValidationUtils.isNullOrEmpty(toCardID) ||
                        ValidationUtils.isNullOrEmpty(amountText) ||
                        ValidationUtils.isNullOrEmpty(password)) {
                    JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                double amount = Double.parseDouble(amountText);
                if (!ValidationUtils.validateAmount(amount)) {
                    JOptionPane.showMessageDialog(this, "转账金额必须大于0且最多两位小数", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                if (!ValidationUtils.validateCardNumber(toCardID)) {
                    JOptionPane.showMessageDialog(this, "转入卡号必须为16位数字", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 检查转出卡是否挂失 - 关键修改点
                if (cardDAO.isCardReportedLoss(fromCardID)) {
                    JOptionPane.showMessageDialog(this, "转账失败：转出卡已挂失！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 检查转入卡是否挂失 - 关键修改点
                if (cardDAO.isCardReportedLoss(toCardID)) {
                    JOptionPane.showMessageDialog(this, "转账失败：转入卡已挂失！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                // 执行转账操作
                boolean success = cardDAO.transfer(fromCardID, toCardID, password, amount);
                if (success) {
                    JOptionPane.showMessageDialog(this, "转账成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    // 清空输入字段
                    amountField.setText("");
                    passwordField.setText("");
                    toCardField.setText("");
                } else {
                    // 转账失败可能原因：密码错误、余额不足或转入卡不存在
                    double balance = cardDAO.getCardBalance(fromCardID);
                    if (amount > balance) {
                        JOptionPane.showMessageDialog(this, "转账失败：余额不足！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    } else if (!cardDAO.cardExists(toCardID)) {
                        JOptionPane.showMessageDialog(this, "转账失败：转入卡不存在！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(this, "转账失败：密码错误！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    }
                }
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(this, "请输入有效的金额数字", "格式错误", JOptionPane.ERROR_MESSAGE);
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        buttonPanel.add(transferButton);

        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        return mainPanel;
    }

    private JPanel createLossReportPanel() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        JLabel titleLabel = new JLabel("卡片挂失/解挂");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("操作信息"),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 银行卡选择
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("选择银行卡:"), gbc);

        JComboBox<String> cardComboBoxLossReport = new JComboBox<>();
        cardComboBoxLossReport.setPreferredSize(new Dimension(250, 30));
        try {
            List<Card> cards = cardDAO.getCardsByCustomerId(Integer.parseInt(customerId));
            for (Card card : cards) {
                cardComboBoxLossReport.addItem(card.getCardID());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载银行卡信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
        gbc.gridx = 1;
        formPanel.add(cardComboBoxLossReport, gbc);

        // 密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("输入密码:"), gbc);

        JPasswordField passwordFieldLossReport = new JPasswordField(20);
        passwordFieldLossReport.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(passwordFieldLossReport, gbc);

        // 按钮面板 - 双按钮布局
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));

        JButton lossReportButton = new JButton("确认挂失");
        lossReportButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        lossReportButton.setPreferredSize(new Dimension(150, 35));

        JButton cancelLossButton = new JButton("取消挂失");
        cancelLossButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        cancelLossButton.setPreferredSize(new Dimension(150, 35));
        cancelLossButton.setEnabled(false); // 初始禁用

        // 卡片选择监听器 - 动态更新按钮状态
        cardComboBoxLossReport.addActionListener(e -> {
            String selectedCard = (String) cardComboBoxLossReport.getSelectedItem();
            if (selectedCard != null) {
                try {
                    Card card = cardDAO.getCardByID(selectedCard);
                    if (card != null) {
                        boolean isReported = "是".equals(card.getIsReportLoss());
                        lossReportButton.setEnabled(!isReported);
                        cancelLossButton.setEnabled(isReported);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(this, "获取卡片状态失败", "错误", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        // 初始加载时检查第一个卡片状态
        if (cardComboBoxLossReport.getItemCount() > 0) {
            cardComboBoxLossReport.setSelectedIndex(0);
        }

        // 挂失按钮事件
        lossReportButton.addActionListener(e -> {
            String cardID = (String) cardComboBoxLossReport.getSelectedItem();
            String password = new String(passwordFieldLossReport.getPassword());

            try {
                if (ValidationUtils.isNullOrEmpty(cardID) || ValidationUtils.isNullOrEmpty(password)) {
                    JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                boolean success = cardDAO.reportLoss(cardID, password);
                if (success) {
                    JOptionPane.showMessageDialog(this, "挂失成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    passwordFieldLossReport.setText("");

                    // 更新按钮状态
                    lossReportButton.setEnabled(false);
                    cancelLossButton.setEnabled(true);
                } else {
                    JOptionPane.showMessageDialog(this, "挂失失败：密码错误！", "操作失败", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 取消挂失按钮事件
        cancelLossButton.addActionListener(e -> {
            String cardID = (String) cardComboBoxLossReport.getSelectedItem();
            String password = new String(passwordFieldLossReport.getPassword());

            try {
                if (ValidationUtils.isNullOrEmpty(cardID) || ValidationUtils.isNullOrEmpty(password)) {
                    JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                boolean success = cardDAO.reportCancel(cardID, password);
                if (success) {
                    JOptionPane.showMessageDialog(this, "取消挂失成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    passwordFieldLossReport.setText("");

                    // 更新按钮状态
                    lossReportButton.setEnabled(true);
                    cancelLossButton.setEnabled(false);
                } else {
                    JOptionPane.showMessageDialog(this, "取消挂失失败：密码错误！", "操作失败", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        buttonPanel.add(lossReportButton);
        buttonPanel.add(cancelLossButton);

        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        return mainPanel;
    }

    private JPanel createChangePasswordPanel() {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JPanel headerPanel = new JPanel();
        headerPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        JLabel titleLabel = new JLabel("修改密码");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
        headerPanel.add(titleLabel);
        mainPanel.add(headerPanel, BorderLayout.NORTH);

        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("密码修改"),
                BorderFactory.createEmptyBorder(15, 15, 15, 15)
        ));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 银行卡选择
        gbc.gridx = 0;
        gbc.gridy = 0;
        formPanel.add(new JLabel("选择银行卡:"), gbc);

        JComboBox<String> cardComboBoxChangePassword = new JComboBox<>();
        cardComboBoxChangePassword.setPreferredSize(new Dimension(250, 30));
        try {
            List<Card> cards = cardDAO.getCardsByCustomerId(Integer.parseInt(customerId));
            for (Card card : cards) {
                cardComboBoxChangePassword.addItem(card.getCardID());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "加载银行卡信息失败！", "错误", JOptionPane.ERROR_MESSAGE);
        }
        gbc.gridx = 1;
        formPanel.add(cardComboBoxChangePassword, gbc);

        // 旧密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(new JLabel("旧密码:"), gbc);

        JPasswordField oldPasswordField = new JPasswordField(20);
        oldPasswordField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(oldPasswordField, gbc);

        // 新密码
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(new JLabel("新密码 (6位数字):"), gbc);

        JPasswordField newPasswordField = new JPasswordField(20);
        newPasswordField.setPreferredSize(new Dimension(250, 30));
        gbc.gridx = 1;
        formPanel.add(newPasswordField, gbc);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 20));
        JButton changePasswordButton = new JButton("确认修改");
        changePasswordButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        changePasswordButton.setPreferredSize(new Dimension(150, 35));
        changePasswordButton.addActionListener(e -> {
            String cardID = (String) cardComboBoxChangePassword.getSelectedItem();
            String oldPassword = new String(oldPasswordField.getPassword());
            String newPassword = new String(newPasswordField.getPassword());

            try {
                // 简单验证
                if (ValidationUtils.isNullOrEmpty(cardID) ||
                        ValidationUtils.isNullOrEmpty(oldPassword) ||
                        ValidationUtils.isNullOrEmpty(newPassword)) {
                    JOptionPane.showMessageDialog(this, "请填写所有必填字段", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 检查卡是否挂失 - 关键修改点
                if (cardDAO.isCardReportedLoss(cardID)) {
                    JOptionPane.showMessageDialog(this, "密码修改失败：该卡已挂失！", "操作失败", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                if (!ValidationUtils.validatePassword(newPassword)) {
                    JOptionPane.showMessageDialog(this, "新密码必须为6位数字", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                // 执行密码修改
                boolean success = cardDAO.changePassword(cardID, oldPassword, newPassword);
                if (success) {
                    JOptionPane.showMessageDialog(this, "密码修改成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
                    // 清空输入字段
                    oldPasswordField.setText("");
                    newPasswordField.setText("");
                } else {
                    // 密码修改失败只可能是旧密码错误（因为挂失卡已提前检查）
                    JOptionPane.showMessageDialog(this, "密码修改失败：旧密码错误！", "操作失败", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            } catch (Exception ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(this, "操作失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        buttonPanel.add(changePasswordButton);

        mainPanel.add(formPanel, BorderLayout.CENTER);
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
        return mainPanel;
    }

       }